package com.szx.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.szx.usercenter.domain.UserFileNumber;
import com.szx.usercenter.mapper.UserFileNumberMapper;
import com.szx.usercenter.service.UserFileNumberService;
import com.szx.usercenter.util.JwtHelper;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * @author yikonsh
 * @description 针对表【user_file_number】的数据库操作Service实现
 * @createDate 2024-06-04 17:35:24
 */
@Service
public class UserFileNumberServiceImpl extends ServiceImpl<UserFileNumberMapper, UserFileNumber>
        implements UserFileNumberService {

    /**
     * 初始化用户容量
     */
    @Override
    public void initUserFileNumber(Long userId) {
        UserFileNumber userFileNumber = new UserFileNumber();
        userFileNumber.setUserId(userId);
        userFileNumber.setCurrentNumber(0L);
        // 默认5GB的容量，5GB=5*1024*1024*1024
        userFileNumber.setAllNumber(5368709120L);
        save(userFileNumber);
    }

    /**
     * 更新使用容量
     */
    @Override
    public void updateCurrentNumber(Long fileSize, Long userId) {
        LambdaQueryWrapper<UserFileNumber> qw = new LambdaQueryWrapper<>();
        qw.eq(UserFileNumber::getUserId, userId);
        UserFileNumber fileNumber = this.getOne(qw);

        LambdaUpdateWrapper<UserFileNumber> uw = new LambdaUpdateWrapper<>();
        uw.set(UserFileNumber::getCurrentNumber, fileNumber.getCurrentNumber() + fileSize);
        uw.eq(UserFileNumber::getUserId, userId);

        this.update(uw);
    }

    /**
     * 获取用户使用容量和总容量
     */
    @Override
    public UserFileNumber getUserFileNumber(HttpServletRequest request) {
        LambdaQueryWrapper<UserFileNumber> qw = new LambdaQueryWrapper<>();
        qw.eq(UserFileNumber::getUserId, JwtHelper.getLoginId(request));
        return this.getOne(qw);
    }

    /**
     * 更新用户容量
     *
     * @param userId         用户ID
     * @param newTotalNumber 新的容量
     * @return
     */
    @Override
    public boolean updateUserNumber(Long userId, Long newTotalNumber) {
        // 先查询这个用户是否有，没有就新增
        LambdaQueryWrapper<UserFileNumber> qw = new LambdaQueryWrapper<>();
        qw.eq(UserFileNumber::getUserId, userId);

        UserFileNumber one = this.getOne(qw);
        if (one != null) {
            return update(new LambdaUpdateWrapper<UserFileNumber>()
                    .eq(UserFileNumber::getUserId, userId)
                    .set(UserFileNumber::getAllNumber, newTotalNumber)
            );
        } else {
            UserFileNumber userFileNumber = new UserFileNumber();
            userFileNumber.setUserId(userId);
            userFileNumber.setAllNumber(newTotalNumber);
            userFileNumber.setCurrentNumber(0L);
            return save(userFileNumber);
        }
    }
}
